#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include <fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>

int main(int argc,char* argv[])
{
    if (argc <3)
    {
        printf("请命令行输入3个\n");
        exit(-1);
    }

    struct stat st;
    int ret = stat(argv[1],&st);
    if (-1==ret)
    {
        printf("获取文件状态失败：%m\n");
        exit(-1);
    }
    int fdSrc = open(argv[1],O_RDONLY);
    if (-1==fdSrc)
    {
        printf("打开待拷贝文件失败%m\n");
        exit(-1);
    }
    char dstName[256]={0};
    if (st.st_mode&S_IFDIR)
    {
        printf("%s是个目录\n",argv[1]);
        //移动 拷贝后删除


        char srcName[56]={0};
        char* p = argv[1];
        int len = strlen(p);
        p+=len-1;
        int k = 0;
        while (*p!='/')
        {
            srcName[k]=*p;
            p--;
            k++;
        }
        char t;
        for (int i=0;i<k/2;i++)
        {
            t = srcName[i];
            srcName[i]=srcName[k-i-1];
            srcName[k-i-1]=t;
        }
        printf("%s\n",srcName);
        sprintf(dstName,"%s/%s",argv[2],srcName);


    }else
    {
        printf("%s是个普通文件\n",argv[1]);
        //重命名 然后删除
        sprintf(dstName,"%s",argv[2]);
    }
    int fdDst = open(dstName,O_WRONLY|O_CREAT,0666);
    if (-1==fdDst)
    {
        printf("打开拷贝文件失败%m\n");
        exit(-1);
    }
    printf("创建拷贝文件\n");
    int r;
    char temp[1024];
    while (1)
    {
        r = read(fdSrc,temp,1024);
        if (r>0) //读到了
        {
            write(fdDst,temp,r); //读多少写多少
        }else //没读到
        {
            break;//结束循环
        }
    }

    close(fdSrc);
    close(fdDst);
    unlink(argv[1]); //删除当前源

}